# 导入所需的库
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, accuracy_score
from sklearn.model_selection import GridSearchCV

# 1. 加载数据集
digits = datasets.load_digits()
X = digits.data  # 图像数据
y = digits.target  # 标签数据

# 2. 数据划分：70% 训练集，30% 测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 3. 标准化数据
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 4. 创建 SVM 模型并训练
svm_model = SVC(kernel='rbf', C=1, gamma=0.05)  # RBF 核，C 和 gamma 为超参数
svm_model.fit(X_train, y_train)

# 5. 用测试集进行预测
y_pred = svm_model.predict(X_test)

# 6. 输出分类报告和准确率
print("分类报告：")
print(classification_report(y_test, y_pred))

print(f"准确率: {accuracy_score(y_test, y_pred) * 100:.2f}%")

# 7. 网格搜索优化超参数
param_grid = {'C': [0.1, 1, 10], 'gamma': [0.01, 0.05, 0.1, 1]}
grid_search = GridSearchCV(SVC(kernel='rbf'), param_grid, cv=3)
grid_search.fit(X_train, y_train)

# 8. 输出最佳参数和性能
print("最佳超参数：", grid_search.best_params_)
print("最佳交叉验证得分：", grid_search.best_score_)